import json
import socket

from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

import predict
import torch
from yolo import YOLO

with torch.no_grad():
    yolo = YOLO()


@csrf_exempt
def process(request):
    res = {}
    if request.method == 'POST':
        try:
            # 拿到图片的对象
            photo = request.FILES['images']
            if photo.size / 1024 / 1024 < 2:
                if photo.content_type == 'image/jpeg' or photo.content_type == 'image/jpg' or photo.content_type == 'image/png':
                    try:
                        print('开始处理图片，请等待~')
                        # target = 'http://' + socket.gethostbyname(socket.gethostname()) + ':8000/' + predict.imageProcess(photo, yolo)
                        target = 'http://121.40.123.15:8000/' + predict.imageProcess(photo, yolo)
                        print('图片处理完成！')
                        res = {'status': 'success', 'message': '处理成功', 'img': target}
                    except:
                        print("处理错误")
                        raise Exception
                else:
                    res = {'status': 'fail', 'message': '只能上传jpeg、jpg、png格式的图片!'}
            else:
                res = {'status': 'fail', 'message': '上传的文件超过了2M！'}
        except:
            res = {'status': 'fail', 'message': '服务失败，请重试！'}
        response = HttpResponse(json.dumps(res))
        response["Access-Control-Allow-Origin"] = "*"
        return response
    else:
        response = HttpResponse(json.dumps({'status': 'fail', 'message': '请使用POST请求'}))
        response["Access-Control-Allow-Origin"] = "*"
        return response
